const homedir = require('os').homedir();//获取电脑用户 home 目录
const home = process.env.HOME || homedir
const path = require('path')//内置路径处理工具
const dbPath = path.join(home, '.todo')//自动加上\拼接路径
const fs = require('fs')

const db = {
    read(path = dbPath) {//如果没传path则用dbPath home
        return new Promise((resolve, reject) => {
            fs.readFile(path, { flag: 'a+' }, (error, data) => {
                if (error) {
                    return reject(error)
                }
                let list
                try {//将读取的文件转成字符串
                    list = JSON.parse(data.toString())
                } catch (error2) {
                    list = []//如果读取新数据为空创建新数组存储新任务
                }
                resolve(list)
            })
        })

    },
    write(list, path = dbPath) {
        return new Promise((resolve, reject) => {
            const string = JSON.stringify(list)
            fs.writeFile(path, string + "\n", (error) => {
                //写文件出错
                if (error) {
                    return reject(error)
                }
                resolve()

            })

        })

    }
}
module.exports = db